package com.example.myapplication


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.media.ImageReader
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.view.SurfaceHolder
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var preViewBuilder: CaptureRequest.Builder
    private var imgReader: ImageReader? = null
    private lateinit var mHandler: Handler
    private lateinit var cameraDevice: CameraDevice
    private lateinit var mSession: CameraCaptureSession
    private val camera: CameraManager by lazy {
        getSystemService(Context.CAMERA_SERVICE) as CameraManager
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sf_view.holder?.run {
            addCallback(object : SurfaceHolder.Callback {
                override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
                    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                }

                override fun surfaceDestroyed(p0: SurfaceHolder) {
                }

                override fun surfaceCreated(p0: SurfaceHolder) {
                    initCameraAndPreview()
                }

            })
        }
    }

    @SuppressLint("MissingPermission")
    private fun initCameraAndPreview() {
        val handlerT = HandlerThread("camera2")
        handlerT.start()
        mHandler = Handler(handlerT.looper)
        imgReader =
            ImageReader.newInstance(
                sf_view.width,
                sf_view.height,
                ImageFormat.YUV_420_888,/*maxImages*/
                7
            )
        imgReader?.setOnImageAvailableListener({
            val img = it.acquireLatestImage()
            val plans = img.planes
            Log.e("cameraDemo", "========================>")
            for (p in plans) {
                Log.d("cameraDemo", p.toString())
            }
            Log.e("cameraDemo", "========================>")
            img.close()
        }, mHandler)
        camera.openCamera(camera.cameraIdList[1], object : CameraDevice.StateCallback() {
            override fun onOpened(camera: CameraDevice) {
                cameraDevice = camera
                createPreview()
            }

            override fun onDisconnected(camera: CameraDevice) {
            }

            override fun onError(camera: CameraDevice, error: Int) {
            }
        }, mHandler)
    }

    private fun createPreview() {
        preViewBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
        preViewBuilder.addTarget(imgReader!!.surface)
        cameraDevice.createCaptureSession(
            arrayListOf(sf_view.holder.surface, imgReader?.surface),
            object : CameraCaptureSession.StateCallback() {
                override fun onConfigureFailed(session: CameraCaptureSession) {

                }

                override fun onConfigured(session: CameraCaptureSession) {
                    mSession = session
                    preViewBuilder.set(
                        CaptureRequest.CONTROL_AF_MODE,
                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO
                    )
                    mSession.setRepeatingRequest(
                        preViewBuilder.build(),
                        object : CameraCaptureSession.CaptureCallback() {

                        },
                        mHandler
                    )
                }
            },
            mHandler
        )
    }

    override fun onPause() {
        super.onPause()

    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
    }

}
